<template>
  <div class="course-selection-container">
    <el-page-header @back="goBack" title="返回">
      <template #content>
        <h1>选课中心</h1>
      </template>
    </el-page-header>

    <div v-loading="loading" class="course-content">
      <!-- 搜索和筛选区域 -->
      <div class="filter-section">
        <el-input
          v-model="searchQuery"
          placeholder="搜索课程名称"
          clearable
          @clear="handleSearchClear"
          @keyup.enter="fetchPaidCourses"
          class="search-input"
        >
          <template #append>
            <el-button @click="fetchPaidCourses">
              <el-icon><search /></el-icon>
            </el-button>
          </template>
        </el-input>
      </div>

      <!-- 课程列表 -->
      <div v-if="courses.length > 0" class="course-list">
        <el-row :gutter="20">
          <el-col
            v-for="course in courses"
            :key="course.id"
            :xs="24"
            :sm="12"
            :md="8"
            :lg="6"
            class="course-col"
          >
            <el-card
              shadow="hover"
              class="course-card"
              @click="navigateToPurchase(course)"
            >
              <div class="course-image-container">
                <img :src="getCourseImage(course.couPic)" class="course-image" />
                <div class="price-tag">¥{{ course.couPrice }}</div>
              </div>
              <div class="course-info">
                <h3 class="course-title">{{ course.couName }}</h3>
                <p class="course-intro">{{ course.couIntroduction || '暂无课程介绍' }}</p>
                <div class="course-stats">
                  <span><i class="el-icon-user"></i> {{ course.couCollNum || 0 }}人收藏</span>
                  <span><i class="el-icon-view"></i> {{ course.clicks || 0 }}次浏览</span>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 分页 -->
        <el-pagination
          v-if="total > pageSize"
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          layout="prev, pager, next"
          @current-change="handlePageChange"
          class="pagination"
        />
      </div>

      <!-- 无课程提示 -->
      <el-empty
        v-if="!loading && courses.length === 0"
        description="暂无付费课程"
        class="empty-tip"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import axios from '@/utils/request'
import defaultCourseImage from '@/assets/fault.png'

const router = useRouter()

// 数据状态
const loading = ref(true)
const courses = ref([])
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(0)

// 获取课程图片
const getCourseImage = (imageUrl) => {
  return imageUrl || defaultCourseImage
}

// 获取付费课程
const fetchPaidCourses = async () => {
  try {
    loading.value = true;
    console.log('正在请求付费课程数据...');
    
    const response = await axios.get('http://localhost:8082/spoc/vod/course/paid-courses', {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      },
      // 添加transformResponse确保正确处理原始响应
      transformResponse: [function (data) {
        try {
          // 如果已经是对象则直接返回
          if (typeof data === 'object') return data;
          // 否则尝试解析JSON
          return data ? JSON.parse(data) : [];
        } catch (e) {
          return data;
        }
      }]
    });

    console.log('完整响应:', response);
    
    // 修改这里：直接使用response或response.data取决于实际结构
    const responseData = Array.isArray(response) ? response : 
                        (Array.isArray(response.data) ? response.data : []);
    
    courses.value = responseData;
    total.value = responseData.length;
    
    console.log('处理后的课程数据:', courses.value);
    
    if (courses.value.length === 0) {
      console.warn('获取到了空课程列表，请检查后端API');
    }
    
  } catch (error) {
    console.error('获取付费课程失败:', error);
    console.error('错误详情:', error.response);
    ElMessage.error('获取课程列表失败: ' + (error.response?.data?.message || error.message));
  } finally {
    loading.value = false;
  }
}

// 处理搜索
const handleSearchClear = () => {
  currentPage.value = 1
  fetchPaidCourses()
}

// 分页变化
const handlePageChange = (newPage) => {
  currentPage.value = newPage
  fetchPaidCourses()
}

// 跳转到购买页面
const navigateToPurchase = (course) => {
  router.push({
    name: 'CoursePurchase',
    params: { id: course.id }
  })
}

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 初始化加载数据
onMounted(() => {
  fetchPaidCourses()
})
</script>

<style scoped>
.course-selection-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.course-content {
  margin-top: 20px;
}

.filter-section {
  display: flex;
  margin-bottom: 20px;
  gap: 15px;
}

.search-input {
  width: 300px;
}

.course-list {
  margin-top: 20px;
}

.course-col {
  margin-bottom: 20px;
}

.course-card {
  cursor: pointer;
  height: 100%;
  transition: all 0.3s;
}

.course-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.course-image-container {
  position: relative;
  width: 100%;
  height: 160px;
  overflow: hidden;
  border-radius: 4px;
}

.course-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.price-tag {
  position: absolute;
  bottom: 10px;
  right: 10px;
  background-color: #f56c6c;
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-weight: bold;
}

.course-info {
  padding: 10px;
}

.course-title {
  font-size: 16px;
  margin: 0 0 8px 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.course-intro {
  color: #666;
  font-size: 14px;
  height: 40px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  margin-bottom: 10px;
}

.course-stats {
  display: flex;
  justify-content: space-between;
  color: #888;
  font-size: 12px;
}

.course-stats i {
  margin-right: 4px;
}

.pagination {
  margin-top: 20px;
  justify-content: center;
}

.empty-tip {
  margin-top: 50px;
}
</style>